import { ref } from 'vue';
import api from '../api/api';

// 编辑文章逻辑
export const useEditArticle = (id) => {
  const article = ref({
    title: '',
    content: '',
    id: id || null
  });
  
  const loading = ref(false);
  const error = ref('');
  const successMessage = ref('');
  
  // 更新文章
  const updateArticle = async (title, content, id) => {
    loading.value = true;
    error.value = '';
    successMessage.value = '';
    
    // 仅当内容不是字符串时才序列化
    const processedContent = typeof content === 'string' ? content : JSON.stringify(content);
    
    try {
      const response = await api.put('/articles/auth', {
        id,
        title,
        content: processedContent
      });
      
      if (response.data.code === 1 && response.data.msg === 'success') {
        successMessage.value = response.data.data.message;
        return {
          isSuccess: true
        };
      } else {
        error.value = '更新文章失败';
        return {
          isSuccess: false
        };
      }
    } catch (err) {
      console.error('请求出错:', err);
      error.value = '网络错误，请重试';
      return {
        isSuccess: false
      };
    } finally {
      loading.value = false;
    }
  };
  
  return { 
    article, 
    loading, 
    error, 
    successMessage, 
    updateArticle 
  };
};